package com.sec.android.app.myfiles.facade.cmd;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;

import com.sec.android.app.myfiles.R;
import com.sec.android.app.myfiles.dialog.EditTextDialogFragment;
import com.sec.android.app.myfiles.fragment.AbsMyFilesFragment;
import com.sec.android.app.myfiles.log.SamsungAnalyticsLog;
import com.sec.android.app.myfiles.module.abstraction.FileRecord;
import com.sec.android.app.myfiles.navigation.NavigationInfo;
import com.sec.android.app.myfiles.navigation.NavigationManager;
import com.sec.android.app.myfiles.operation.FileOperationArgs;
import com.sec.android.app.myfiles.operation.FileOperationFragment;
import com.sec.android.app.myfiles.operation.FileOperator;
import com.sec.android.app.myfiles.util.StorageMonitor;

import org.puremvc.java.multicore.interfaces.INotification;
import org.puremvc.java.multicore.patterns.command.SimpleCommand;

import java.util.ArrayList;

public class CompressRecordsCmd extends SimpleCommand implements EditTextDialogFragment.EditTextCallback, FileOperationFragment.PostOperation {

    private Context mContext;

    private EditTextDialogFragment mEditDialog;
    private AbsMyFilesFragment mFragment;
    private ArrayList<FileRecord> mRecordList;
    private FileRecord mDstRecord;

    /**
     * the length of ".zip" is 4
     */
    private static final int MAX_NAME_LENGTH = 46;
    private static final String DOT_ZIP_EXT = ".zip";
    private static final String ZIP_FILE_TYPE_FLAG = "zipType=true";

    @SuppressWarnings("unchecked")
    @Override
    public void execute(INotification notification) {
        Object[] params = (Object[]) notification.getBody();
        mContext = (Context) params[0];
        mFragment = (AbsMyFilesFragment) params[1];
        mRecordList = (ArrayList<FileRecord>) params[2];

        NavigationInfo info = NavigationManager.getInstance(mFragment.getProcessId()).getCurInfo();
        if (info != null) {
            mDstRecord = info.getCurRecord();
            String defaultText = getDefaultTargetName(mRecordList, mDstRecord);
            mEditDialog = new EditTextDialogFragment.Builder()
                    .setEditTextCallback(this)
                    .setTitle(R.string.menu_zip_title)
                    .setOkText(R.string.menu_zip)
                    .setDefaultText(defaultText)
                    .setPostfix(DOT_ZIP_EXT)
                    .setExtraImeOptions(ZIP_FILE_TYPE_FLAG)
                    .build();
            mEditDialog.show(mFragment.getFragmentManager());
        }
    }

    private String getDefaultTargetName(ArrayList<FileRecord> srcList, FileRecord dst) {
        String ret = null;
        if (srcList.size() == 1) {
            FileRecord src = srcList.get(0);
            if (src != null) {
                ret = src.getNameWithoutExt();
            }
        } else {
            ret = dst.isRoot() ? StorageMonitor.getDisplayName(mContext, dst.getFullPath()) : dst.getNameWithoutExt();
        }
        if (ret != null) {
            int length = ret.length();
            if (length > MAX_NAME_LENGTH) {
                ret = ret.substring(0, MAX_NAME_LENGTH);
            }
        }
        return ret + DOT_ZIP_EXT;
    }

    @Override
    public boolean checkNameExist(String inputString) {
        return false;
    }

    @Override
    public boolean checkText(String inputString, Activity activity) {
        boolean bRet = true;
        inputString = inputString.trim();
        if (TextUtils.isEmpty(inputString)) {
            bRet = false;
        } else {
            String resultPath = getResultPath(inputString);
            FileRecord newFileRecord = FileRecord.createFileRecord(mDstRecord.getStorageType(), resultPath);
            if (inputString != null &&
                    (inputString.equals(".") || inputString.equals("..") || inputString.equals(DOT_ZIP_EXT))) {
                mEditDialog.setInputErrorEnabled(true);
                mEditDialog.setInputError(activity.getString(R.string.enter_name));
                bRet = false;
            } else if (newFileRecord != null && newFileRecord.exists(activity)) {
                mEditDialog.setInputErrorEnabled(true);
                mEditDialog.setInputError(activity.getString(R.string.file_name_exist));
                bRet = false;
            }
        }
        return bRet;
    }

    @Override
    public void onOK(String inputString, Activity activity) {
        inputString = inputString.trim();
        String resultPath = getResultPath(inputString);
        FileRecord newFileRecord = FileRecord.createFileRecord(mDstRecord.getStorageType(), resultPath);
        if (checkText(inputString, activity)) {
            mEditDialog.onFinished(true, null, null);
            FileRecord dst = FileRecord.createFileRecord(mDstRecord.getStorageType(), resultPath);
            FileOperationArgs args = new FileOperationArgs();
            args.mSrcList = mRecordList;
            args.mDst = dst;
            if (mFragment != null) {
                if (mFragment.getNavigationInfo() != null)
                    mFragment.getNavigationInfo().setFocusRecord(dst);

                FileOperationFragment fg = FileOperationFragment.createInstance(mContext, mFragment,
                        mFragment.getFragmentManager(), FileOperator.Operation.COMPRESS, args, this);

                fg.show();
            }
        }
        SamsungAnalyticsLog.sendLog(SamsungAnalyticsLog.ScreenPath.ZIP_POPUP, SamsungAnalyticsLog.Event.ZIP, null);
    }

    @Override
    public void onCancel(Activity activity) {
        SamsungAnalyticsLog.sendLog(SamsungAnalyticsLog.ScreenPath.ZIP_POPUP, SamsungAnalyticsLog.Event.CANCEL, null);
    }

    @Override
    public void onResult(FileOperator.Operation opType, boolean bRet, Bundle extras) {
        if (mFragment != null && !mFragment.isDetached()) {
            mFragment.finishActionMode();
        }
    }

    private String getResultPath(String input) {
        return mDstRecord.getFullPath() + "/" + input;
    }
}